import argparse, os, sys, logging, datetime

from protolib import get_app_root

import data

logging.basicConfig(
    level=logging.INFO,
    # filename='MusicRepository.log',
)

logger = logging.getLogger(__name__)

if os.path.exists(os.path.join(get_app_root(), '.CONFIG_LOCATION')):
    with open(os.path.join(get_app_root(), '.CONFIG_LOCATION')) as f:
        config_path = f.read()
else:
    config_path = os.path.join(get_app_root(), 'config.json')

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='Actions', dest='action')

parser.add_argument('-c', '--config', default=config_path, help='Set the path to a different config file')

sync_parser = subparsers.add_parser('sync', help='Sync your library to an external device')
sync_parser.add_argument('file_path', help='Path to the directory that will be synced')
sync_parser.add_argument('-r', '--repair', help='Repair the sync database and exit. The library will not be synced')
sync_parser.add_argument('-f', '--force', '--force-meta-update', help='Force the sync function to overwrite the metadata of already synced tracks')
sync_parser.add_argument('-u', '--update', '--update-meta', help='Updates the metadata of already synced tracks')

scan_parser = subparsers.add_parser('scan', help='Scans for new music files')

scrape_parser = subparsers.add_parser('scrape', help='Scans music files for missing metadata')

repair_parser = subparsers.add_parser('repair', help='Looks for and fixes errors in the database')

delete_parser = subparsers.add_parser('delete', help='Deletes all records in a field of the sync database')
delete_parser.add_argument('field', help='Database field that will be deleted', choices=['music', 'tracks', 'artists', 'albums', 'genres', 'covers'])

args = parser.parse_args()

config_path = args.config

with open(os.path.join(get_app_root(), '.CONFIG_LOCATION'), 'w') as f:
    f.write(config_path)

data.start(config_path)

import scan, scrape, sync, repair

print('%s tracks in database' % len(data.database['music']))
print('%s artists in database' % len(data.database['artists']))
print('%s albums in database' % len(data.database['albums']))
print('%s genres in database' % len(data.database['genres']))
print('%s covers in database' % len(data.database['covers']))

from player import main as start_gui

exit_code = None

match args.action:
    case 'sync':
        if args.repair:
            print('Repairing sync database')
            repair.repair_sync_db(args.sync)
        else:
            print('Syncing library')
            sync.sync(args.sync, force_meta_write=args.force, write_changed_meta=args.update)
    case 'scan':
        print('Scanning for changed files')
        scan.scan()
    case 'scrape':
        print('Scraping existing files')
        scrape.scrape()
    case 'repair':
        print('Repairing database')
        repair.repair_main_db()
    case 'delete':
        if args.delete in ['music', 'tracks']:
            data.database['music'] = {}
            print('Deleted records in field %s' % args.delete)
        elif args.delete == 'artists':
            data.database['artists'] = {}
            print('Deleted records in field %s' % args.delete)
        elif args.delete == 'albums':
            data.database['albums'] = {}
            print('Deleted records in field %s' % args.delete)
        elif args.delete == 'genres':
            data.database['genres'] = {}
            print('Deleted records in field %s' % args.delete)
        elif args.delete == 'covers':
            data.database['covers'] = {}
            print('Deleted records in field %s' % args.delete)
        else:
            exit_code = 1
            print('Invalid field: %s' % args.delete)
    case _:
        print('Starting GUI')
        exit_code = start_gui()

data.stop()

if exit_code:
    sys.exit(exit_code)
